<template>
    <div>
        <el-form
            ref="ruleFormRef"
            :model="userfoin"
            :rules="rules"
            label-width="120px"
            id="inputin"
            class="demo-ruleForm"
        >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userfoin.username" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="userfoin.password" type="password" autocomplete="off" />
            </el-form-item>
        </el-form>
        <el-button type="primary" id="up" @click="YES(ruleFormRef)">登录</el-button>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
//引入axios
import {requert} from '../requert/index'
//导入store的 状态文件
import { useMainStore } from '../store/index'
//导入elements
import { FormInstance, ElMessage } from 'element-plus';
//引入路由
import { useRouter } from 'vue-router';

//获取状态的实例对象
const mainStore = useMainStore()
//表单验证的实例
const ruleFormRef = ref<FormInstance>()
//实例化路由
const router = useRouter()
//双向数据绑定
const userfoin = reactive({
    username: 'admin',
    password: '123456'
})

//表单验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入活动名称', trigger: 'blur' },
        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
    ],
    password:[
        { required: true, message: '请输入活动密码', trigger: 'blur' },
        { min: 3, max: 5, message: '长度在 3 到 5 个数字', trigger: 'blur' },
    ]
})

//进行表单验证
const YES = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            //如果正确发起请求
            const { data } = await requert.post('/login', userfoin)
            console.log(data);
            if (data.meta.status == 400) {
                //状态为400则为失败
                ElMessage({
                    message: '你脑子被驴踢了？错了',
                    type: 'warning',
                })
                //成功进行登录
            } else if (data.meta.status == 200) {
                //存储到本地缓存和容器仓库
                localStorage.setItem("userfoin", JSON.stringify(data.data));
                mainStore.userchange()
                ElMessage({
                    message: '登录成功了，宝贝',
                    type: 'success',
                })
                //跳转路由到home页面
                router.push({ path: '/home' })
            } else {
                ElMessage({
                    message: '你脑子被驴踢了',
                    type: 'warning',
                })
            }
            //表单验证有误
        } else {
           ElMessage.error('用户名错误')
        }
    })
}
</script>

<style>
#inputin {
    margin-top: 200px;
}
#up {
    margin-left: 45%;
}
</style>